<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ContactController
 *
 * @author Poh Nean
 */
class ContactController extends PsController
{

	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'users' => array('@'),
					)), parent::accessRules());
	}

	public function filters()
	{
		return CMap::mergeArray(parent::filters(), array(
					'ajaxOnly 
						+ addEmail'
		));
	}

	public function actionAddEmail($party_id)
	{
		$response = array();

		$newEmail = $_POST['new_email'];
		$success = true;
		if (isset($party_id)) {
			$party = Party::model()->findByPk($party_id);

			switch ($party->type) {
				case 'Contact':
					$contact = $this->loadContactByPartyId($party_id);

					if (empty($contact->email)) {
						$contact->email = $newEmail;
						$success = $contact->save();
					} else {
						$contactDetailType = ContactDetailType::model()->findByAttributes(array(
							'type' => 'Email',
							'subtype' => 'Email',
						));

						$contactDetails = array(
							'contact_detail_type_id' => $contactDetailType->id,
							'text' => $newEmail
						);

						$success = $contact->addContactDetail($contactDetails);
					}
					break;
				case 'User':
				case 'Agency':
					break;
				default:
					break;
			}
		}

		if (!$success) {
			$response['result'] = 'failure';
		} else {
			$response['result'] = 'success';
			$response['new_email'] = $newEmail;
		}

		print (json_encode($response));
	}

	/**
	 * @param integer $id the party id
	 * @return Contact
	 * @throws CHttpException
	 */
	public function loadContactByPartyId($id)
	{
		$contact = Contact::model()->ofCurrentAgency()->findbyAttributes(array(
			'party_id' => $id
		));

		if ($contact == null) {
			throw new PsPageNotFoundException();
		}
		return $contact;
	}

	public function actionCheck()
	{
		$contact = $_GET['contact'];

		$response = array();

		if ($contact['name'] != '') {
			$numMatchSql = "(name LIKE :name)";
			$params = array(
				':name' => trim($contact['name']) . '%',
				':owner_party_id' => Yii::app()->user->getSelectedAgency()->party_id
			);

			if ($contact['mobile'] != '') {
				$numMatchSql .= "+ (mobile LIKE :mobile) ";
				$params[':mobile'] = trim($contact['mobile']) . '%';
			}
			if ($contact['email'] != '') {
				$numMatchSql .= "+ (email LIKE :email) ";
				$params[':email'] = trim($contact['email']) . '%';
			}
			if ($contact['landline'] != '') {
				$numMatchSql .= "+ (landline LIKE :landline) ";
				$params[':landline'] = trim($contact['landline']) . '%';
			}

			$sql = "SELECT *, " . $numMatchSql . "
                AS num_match 
                FROM `contact` 
                WHERE owner_party_id = :owner_party_id AND name LIKE :name AND deleted = 0
                HAVING num_match > 0 ORDER BY num_match DESC 
                LIMIT 10";

			$results = Yii::app()->db->createCommand($sql)->queryAll(true, $params);

			$response['result'] = 'success';
			$response['data'] = $results;
		} else {
			$response['result'] = 'failure';
			$response['errorMsg'] = 'Name is empty';
		}

		print CJSON::encode($response);
	}

	/**
	 * Find all action. Used by ajax function in select clients to retrieve 
	 * a full list of contacts of the agent.
	 * @param type $term 
	 */
	public function actionFind($term)
	{
		$response = array();

		$data = array();

		$data["contacts"] = Contact::model()->notRemoved()->ofCurrentAgency()->findAll(array(
			'condition' => "name LIKE :name",
			'params' => array(':name' => "%$term%"),
			'limit' => 25,
			'order' => 'name ASC'
		));

		$response['result'] = 'success';
		$response['data'] = $data;

		print CJSON::encode($response);
	}

	public function actionFindBillingParty($term = '')
	{

		$response = array();
		$isLicenseNo = false;
		$response['input'] = $term;

		$data = array();

		if (strlen($term) > 0) {

			$contactSql = '';
			$agentSql = '';
			$agencySql = '';

			if (!empty($_GET['parties'])) {
				$params = array();

				if (in_array('contacts', $_GET['parties'])) {
					$contactSql = 
						"(SELECT party_id, address_formatted as address, id, name, '' as agency_name, 'Contact' as `model`, '' as license_no, CONCAT(`mobile`, ' ', `landline`) as `info` 
						FROM `contact` 
						WHERE owner_party_id = :owner_party_id AND name LIKE :term)";
					$params[':owner_party_id'] = Yii::app()->user->getSelectedAgency()->party_id;
				}

				if (in_array('agents', $_GET['parties'])) {
					$union = array_search('agents', $_GET['parties']) == 0 ? '' : 'UNION';
					$agentSql = $union . 
						" (SELECT u.party_id as party_id, a.address_formatted as address, u.id as id, u.name as name, a.name as agency_name, 'User' as model, u.license_no as license_no, CONCAT(u.license_no, ' ', a.name) as `info` 
						FROM `user` u JOIN `agency` a ON u.agency_id = a.id 
						WHERE (u.name LIKE :term OR u.license_no LIKE :term))";
				}
				if (in_array('agencies', $_GET['parties'])) {
					$union = array_search('agencies', $_GET['parties']) == 0 ? '' : 'UNION';
					$agencySql = $union . 
						" (SELECT party_id, address_formatted as address, id, name, '' as agency_name, 'Agency' as `model`, '' as license_no,  address_formatted as info 
						FROM `agency` 
						WHERE name LIKE :term)";
				}
				
				$params[':term'] = '%' . $term . '%';

				$sql = "SELECT * FROM 
					(
						" . $contactSql . $agentSql . $agencySql . "
					) AS t
					
					ORDER BY t.name
					LIMIT 25";



				$entities = Yii::app()->db->createCommand($sql)->queryAll(true, $params);


				if (!empty($entities)) {
					foreach ($entities as &$entity) {
						if (is_null($entity['party_id'])) {
							$modelId = $entity['id'];
							$modelClass = $entity['model'];
							$instance = $modelClass::model()->findByPk($modelId);
							$entity['party_id'] = $instance->getPartyId();
						}
					}
				}



				$isLicenseNo = preg_match('/^[rRpP].*[a-zA-Z]$/i', $term);
				$usersCriteria = new CDbCriteria();
				$usersCriteria->with = array('agency');
				$usersCriteria->together = true;
				$usersCriteria->addCondition('t.license_no LIKE :term OR t.name LIKE :term');
//				$usersCriteria->addCondition('t.agency_id <> :agencyId');  //we bill only external agents
				$usersCriteria->params = array();
				$usersCriteria->params[':term'] = '%' . $term . '%';
//				$usersCriteria->params[':agencyId'] = Yii::app()->user->model->agency_id;
				$usersCriteria->limit = 25;

				$users = User::model()->findAll($usersCriteria);

				if (empty($users) && $isLicenseNo) {
					$newUser = null;
//					$newUser = PsCEADataGrabber::grabAgent($term);
					if (!empty($newUser)) {
						$agent = array();
						$agent['model'] = 'User';
						$agent['party_id'] = $newUser->party_id;
						$agent['id'] = $newUser->id;
						$agent['name'] = $newUser->name;
						$agent['license_no'] = $newUser->license_no;

						$agent['info'] = $newUser->license_no . ' ' . $newUser->agency->name;
						$agent['address'] = $newUser->agency->address_formatted;
						$entities[] = $agent;
					}
				}
			}
		}

		$data['entities'] = $entities;
		$response['isCEALicense'] = $isLicenseNo;
		$response['result'] = 'success';
		$response['data'] = $data;
		$response['try'] = $_GET['parties'];

		print CJSON::encode($response);
	}

}

?>
